//
//  IMEngine.swift
//  onemeetingmac
//
//  Created by 张衡 on 2020/6/3.
//  Copyright © 2020 onemeeting. All rights reserved.
//

import Foundation

class IMEngine: NSObject {
    
    static let shared = IMEngine()
    
    
    func sdkAuto() {
        let config = V2TIMSDKConfig()
        config.logLevel = .LOG_NONE
        V2TIMManager.sharedInstance()?.initSDK(SDKAPPID, config: config, listener: self)
        V2TIMManager.sharedInstance()?.add(self)
        V2TIMManager.sharedInstance()?.setGroupListener(self)
    }
    
    func oldSdkAuto() {
        let config = TIMSdkConfig()
        config.logLevel = .LOG_NONE
        config.sdkAppId = SDKAPPID
        TIMManager.sharedInstance()?.initSdk(config)
        TIMManager.sharedInstance()?.add(self)
    }
    
    func oldLogin(id:String,succ:os_block_t?=nil,fail:(ResultFail_opt)?=nil) {
        let param = TIMLoginParam()
        param.identifier = id
        param.userSig = GenerateTestUserSig.genTestUserSig(id)
        TIMManager.sharedInstance()?.login(param, succ: {
            print("登录成功")
            if succ != nil {
                succ!()
            }
        }, fail: { (code, msg) in
            print("登录失败\(code),\(msg ?? "未知")")
            if fail != nil {
                fail!(Int(code),msg)
            }
        })
    }
    
    
    func oldDeleteGroup(groupId:String,succ:os_block_t?=nil,fail:ResultFail_opt?=nil)  {
        TIMGroupManager.sharedInstance()?.deleteGroup(groupId, succ: {
            if succ != nil {
                succ!()
            }
        }, fail: { (code, msg) in
            if fail != nil {
                fail!(Int(code),msg)
            }
        })
    }
    
    func unInit() {
        V2TIMManager.sharedInstance()?.remove(self)
        //V2TIMManager.sharedInstance()?.unInitSDK()
        /*
        V2TIMManager.sharedInstance()?.logout({
            V2TIMManager.sharedInstance()?.unInitSDK()
        }, fail: { (code, msg) in

        })
        */
        
        
    }
    
    func logout() {
        V2TIMManager.sharedInstance()?.logout({
            print("退出登录成功")
        }, fail: { (code, msg) in
            print("退出登录失败code=\(code),msg=\(msg ?? "未知")")
        })
    }
    
    func login(id:String,succ:(os_block_t)?=nil,fail:(ResultFail_opt)?=nil) {
        let userSig = GenerateTestUserSig.genTestUserSig(id)
        V2TIMManager.sharedInstance()?.login(id, userSig: userSig, succ: {
            print("登录成功")
            if succ != nil {
                succ!()
            }
        }, fail: { (code, msg) in
            print("登录失败\(code),\(msg ?? "未知")")
            if fail != nil {
                fail!(Int(code),msg)
            }
        })
        
    }
    
    func getUsersInfo(groupIDs:[String],succ:OneUserFullInfoSuccess?=nil,fail:ResultFail_opt?=nil) {
        V2TIMManager.sharedInstance()?.getUsersInfo(groupIDs, succ: { (result) in
            guard let list = result  else {
                return
            }
            if succ != nil {
                let zhList = list.map { (info) -> OneUserFullInfo in
                    var zhInfo = OneUserFullInfo()
                    zhInfo.nickName = info.nickName
                    zhInfo.faceURL = info.faceURL
                    zhInfo.userID = info.userID
                    return zhInfo
                }
                succ!(zhList)
            }
        }, fail: { (code, msg) in
            print("获取失败\(code),\(msg ?? "未知")")
            if fail != nil {
                fail!(Int(code),msg)
            }
        })
        
    }
    
    func getGroupMembersInfo(groupID:String,memberList:[String],succ:OneGroupMemberSuccess?=nil,fail:ResultFail_opt?=nil) {
        V2TIMManager.sharedInstance()?.getGroupMembersInfo(groupID, memberList: memberList, succ: { (result) in
            guard let list = result  else {
                return
            }
            print("获取成功")
            if succ != nil {
                let zhList = list.map { (info) -> OneGroupMemberInfo in
                    var zhInfo = OneGroupMemberInfo()
                    zhInfo.nickName = info.nickName
                    zhInfo.faceURL = info.faceURL
                    zhInfo.friendRemark = info.friendRemark
                    zhInfo.userID = info.userID
                    zhInfo.nameCard = info.nameCard
                    return zhInfo
                }
                succ!(zhList)
            }
        }, fail: { (code, msg) in
            print("获取失败\(code),\(msg ?? "未知")")
            if fail != nil {
                fail!(Int(code),msg)
            }
        })
        
    }
    
    func updateNickName(name:String,succ:os_block_t?=nil,fail:ResultFail_opt?=nil) {
        let info = V2TIMUserFullInfo()
        info.nickName = name
        V2TIMManager.sharedInstance()?.setSelfInfo(info, succ: {
            print("修改个人信息成功")
            if succ != nil {
                succ!()
            }
        }, fail: { (code, msg) in
            print("修改个人信息失败\(code),\(msg ?? "未知")")
            if fail != nil {
                fail!(Int(code),msg)
            }
        })
    }
    
    func getJoinedGroupList(groupId:String,succ:ResultBool?=nil,fail:ResultFail_opt?=nil) {
        V2TIMManager.sharedInstance()?.getJoinedGroupList({ (result) in
            let findRuslt = result?.filter({ (info) -> Bool in
                return (info.groupID==groupId)
            })
            if succ != nil {
                let isok = findRuslt!.count > 0
                succ!(isok)
            }
        }, fail: { (code, msg) in
            if fail != nil {
                fail!(Int(code),msg)
            }
        })
    }
    
    func getGroupInfo(groupId:String,succ:ResultBool?=nil,fail:ResultFail_opt?=nil) {
        V2TIMManager.sharedInstance()?.getGroupsInfo([groupId], succ: { (result) in
            let findRuslt = result?.filter({ (infoRsult) -> Bool in
                return  infoRsult.resultCode==0
            })
            guard let isok = findRuslt else {
                if succ != nil {
                    succ!(false)
                }
                return
            }
            
            if succ != nil {
                succ!(isok.count > 0)
            }
        }, fail: { (code, msg) in
            if fail != nil {
                fail!(Int(code),msg)
            }
        })
    }
    
    func createGroup(name:String,groupId:String,succ:os_block_t?=nil,fail:ResultFail_opt?=nil) {
        let info = V2TIMGroupInfo()
        info.groupName = name
        info.groupID = groupId
        info.groupType = "ChatRoom"
        let memberList:[V2TIMCreateGroupMemberInfo] = []
        /*
        let memberInfo =  TIMCreateGroupMemberInfo()
        memberInfo.member = "VINSON"
        memberList.append(memberInfo)
        */
        V2TIMManager.sharedInstance()?.createGroup(info, memberList: memberList, succ: { (result) in
            print("创建群组成功")
            if succ != nil {
                succ!()
            }
        }, fail: { (code, msg) in
            print("创建群组失败\(code),\(msg ?? "未知")")
            if fail != nil {
                fail!(Int(code),msg)
            }
        })
        
    }
    
    func dismissGroup(groupId:String,succ:os_block_t?=nil,fail:ResultFail_opt?=nil)  {
        V2TIMManager.sharedInstance()?.dismissGroup(groupId, succ: {
            if succ != nil {
                succ!()
            }
        }, fail: { (code, msg) in
            if fail != nil {
                fail!(Int(code),msg)
            }
        })
    }
    
    
    func joinGroup(groupId:String,succ:os_block_t?=nil,fail:ResultFail_opt?=nil) {
        V2TIMManager.sharedInstance()?.joinGroup(groupId, msg: "\(groupId) 用户进入房间了", succ: {
            print("加入群组成功")
            if succ != nil {
                succ!()
            }
        }, fail: { (code, msg) in
            print("加入群组失败\(code),\(msg ?? "未知")")
            if fail != nil {
                fail!(Int(code),msg)
            }
        })
    }
    
    func send(t:String,groupId:String,succ:(()->())?=nil) {
        V2TIMManager.sharedInstance()?.sendGroupTextMessage(t, to: groupId, priority: V2TIMMessagePriority.PRIORITY_DEFAULT, succ: {
            print("发送文本消息成功")
            if succ != nil {
                succ!()
            }
        }, fail: { (code, msg) in
            print("发送文本消息失败\(code),\(msg ?? "未知")")
        })
        
    }
    
    func conversationSend(t:String,groupId:String) {
        let text = TIMTextElem.init()
        text.text = t
        let msg = TIMMessage.init()
        msg.add(text)
        let convers = TIMManager.sharedInstance()?.getConversation(TIMConversationType.GROUP, receiver: groupId)
        convers?.send(msg, succ: {
            print("发送文本消息成功")
        }, fail: { (code, msg) in
            print("发送文本消息失败\(code),\(msg ?? "未知")")
        })
    }
    
    
}


extension IMEngine:V2TIMSDKListener {
    func onConnecting() {
        print("正在连接到腾讯云服务器")
    }
    
    func onConnSucc() {
        print("已经成功连接到腾讯云服务器")
    }
    
}
extension IMEngine:V2TIMGroupListener {
    func onMemberInfoChanged(_ changeInfoList: [V2TIMGroupMemberChangeInfo]!) {
        
    }
    
    func onGroupInfoChanged(_ changeInfoList: [V2TIMGroupChangeInfo]!) {
        
    }
}

extension IMEngine:V2TIMSimpleMsgListener {
    func onGroupDismissed(_ groupID: String!, opUser: V2TIMGroupMemberInfo!) {
        if groupID.isCurretRoom() {
            MTNot.onExitRoom(isLeave: true)
        }
    }
    
    func onRecvC2CTextMessage(_ msgID: String!, sender info: V2TIMUserInfo!, text: String!) {
        
    }
    
    func onRecvC2CCustomMessage(_ msgID: String!, sender info: V2TIMUserInfo!, customData data: Data!) {
        
    }
    
    func onRecvGroupTextMessage(_ msgID: String!, groupID: String!, sender info: V2TIMGroupMemberInfo!, text: String!) {
        if groupID.isCurretRoom() != true {
            return
        }

        if Td.sh().lastmessge == text {
            return
        }
        Td.sh().lastmessge = text
        
        guard let mode = WebSocketMode.deserialize(from: text.toDict()) else { return }
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+0.1) {
            switch mode.cmd {
            case mt_wss_downHand:
                MTNot.postNotHandUp(isok: false,userid: mode.userid)
            case mt_wss_raiseHand:
                MTNot.postNotHandUp(isok: true,userid: mode.userid)
            case mt_wss_host_downAllHand:
                MTNot.postNotAllHandUp()
            case mt_wss_host_downUserHand:
                if mode.userid?.isCurret() == true {
                    MTNot.postNotHandUp(isok: false)
                }
            case mt_wss_host_removeUser:
                if mode.userid?.isCurret() == true {
                    MTNot.onExitRoom(isLeave: true)
                    showAlert_msg("你已经被主持人移出了会议")
                }
            case mt_wss_modifyName:
                if let name = mode.username {
                    MTNot.postModyName(name: name, userid: mode.userid)
                }
            case mt_wss_host_exit:
                MTNot.onExitRoom(isLeave: true)
            case mt_wss_host_muteUser:
                if mode.userid?.isCurret() == true {
                    Td.sh().cloud.isALLMute = true
                    MTNot.postNotMute()
                }
            case mt_wss_host_unMuteUser:
                if mode.userid?.isCurret() == true {
                    Td.sh().cloud.isALLMute = false
                    MTNot.postNotMute()
                }
            case mt_wss_host_muteAll:
                Td.sh().cloud.isALLMute = true
                MTNot.postNotMute()
            case mt_wss_host_unmuteAll:
                Td.sh().cloud.isALLMute = false
                MTNot.postNotMute()
            case mt_wss_barrage:
                if let txt = mode.txt {
                    MTNot.postNotBarrge(text: txt,userid: mode.userid,userName: mode.username)
                }
            case mt_wss_host_focuseUser:
                MTNot.postFocusID(userID: mode.userid!)
                //直播模式
            case mt_wss_enter_toAudience:
                if mode.touserid?.isCurret() == true {
                    MTNot.postAddAdc(userId: mode.userid, name: mode.username)
                }
            case mt_wss_enter_audience:
                MTNot.postAddAdc(userId: mode.userid, name: mode.username)
                if let userid = mode.userid {
                    IMcmd.shared.toAudience(toUserId: userid)
                }
            case mt_wss_exit_audience:
                MTNot.postDeleteAdc(userId: mode.userid)
            case mt_wss_send2UpMic:
                if let userid = mode.userid {
                    if Td.sh().usr.remote.count+1 < 4 {
                       IMcmd.shared.accept2UpMic(toUserId: userid)
                    }else {
                        show_msg("上麦人数满了")
                    }
                }
            case mt_wss_acceptUpmic:
                if mode.touserid?.isCurret() == true {
                    MTNot.postNotUpMicSwitch(isok: true, isConfirm: false)
                }
            case mt_wss_message:
                if mode.touserid?.isCurret() == true {
                    MTNot.postNotMessage(formId: mode.userid, text: mode.txt)
                }
            case mt_wss_host_swAnchor:
                if mode.userid?.isCurret() == true {
                    MTNot.postNotUpMicSwitch(isok: true, isConfirm: true)
                }
            case mt_wss_host_swAudience:
                if mode.userid?.isCurret() == true {
                    MTNot.postNotUpMicSwitch(isok: false, isConfirm: false)
                }
            case mt_wss_reqUpmic:
                if String.isHostId() {
                    if Td.sh().cloud.disLink == false {
                         MTNot.postNotUpMicRequest(isok: true,userid: mode.userid!)
                    }
                }
            case mt_wss_host_stopShare:
                Td.sh().cloud.disSd = true
                if Td.sh().sd.isSding == true {
                    let mode = StreamMode.init(userId: Td.sh().params.userId!, available: false)
                    NotificationCenter.default.post(name: MTSendStreamNotification, object: mode)
                }
            case mt_wss_host_allowShare:
                Td.sh().cloud.disSd = false
            case mt_wss_host_disDanmu:
                Td.sh().cloud.disBararage = true
            case mt_wss_host_danmu:
                Td.sh().cloud.disBararage = false
            case mt_wss_host_notAllowToRole:
                Td.sh().cloud.disLink = true
            case mt_wss_host_allowToRole:
                Td.sh().cloud.disLink = false
            default:
                break
            }
        }
    }
    
    
    
    func onRecvGroupCustomMessage(_ msgID: String!, groupID: String!, sender info: V2TIMGroupMemberInfo!, customData data: Data!) {
        
    }
    
}

extension IMEngine:TIMMessageListener {
    
    func onNewMessage(_ msgs: [Any]!) {
        
        guard let elems = (msgs as? [TIMMessage]) else {
            return
        }
        guard let elem = elems[0].getElem(elems[0].elemCount()-1) as? TIMTextElem else {
            return
        }
        
        let mode = WebSocketMode.deserialize(from: elem.text.toDict())
        
        if mode?.roomid?.isCurretRoom() != true {
            return
        }
        
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+0.1) {
            
        }
    }
}


